package com.emspost.utils;

import cn.hutool.crypto.digest.DigestUtil;

import java.util.*;

import net.sf.json.JSONObject;

public class GenPaySingUtils {

    //6159F0B5DC154074B82306C6ED7C2F56

    public static void main(String[] args) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("mailNum","1019908400866");
        paramMap.put("payType","6");
        paramMap.put("refundAmt","2.00");
        paramMap.put("dataSrcSys","1");
        paramMap.put("sign","D4418F073D6E352A86F135F005625DB0");
        JSONObject signJSON = JSONObject.fromObject(paramMap);
        getSignByKey(signJSON, "6159F0B5DC154074B82306C6ED7C2F56");

    }

    /**
     * 签名.
     *
     * @param json 待签名数据
     * @param key  密钥
     * @return 签名!
     */
    public static String getSignByKey(JSONObject json, String key) {
        String sign = "";
        if (json != null && !json.isEmpty()) {
            List<String> list = new ArrayList<>();
            for (Object s : json.keySet()) {
                Object v = json.get(s);
                if (!"sign".equals(s) && v != null && !"".equals(v) && !"null".equals(v.toString())) {
                    String kv = s + "=" + json.get(s);
                    list.add(kv);
                }
            }
            Collections.sort(list);
            StringBuffer buffer = new StringBuffer();
            for (String string : list) {
                buffer.append(string).append("&");
            }
            System.out.println("签名第一步：" + buffer.toString());
            buffer.append("key=").append(key);
            System.out.println("签名第二步：" + buffer.toString());
            sign = DigestUtil.md5Hex(buffer.toString()).toUpperCase();
            System.out.println("签名第三步：" + sign);
        }
        return sign;
    }
}
